/*
 * CAnthill.cpp
 *
 *  Created on: 14 Oct 2012
 *      Author: Mario Kleinsasser
 *		Time:	17:19:53
 */

#include <iostream>
#include <typeinfo>
#include "CAnthill.h"
#include "CAnt.h"
#include "CEnvironment.h"
#include <time.h>
#include <stdlib.h>
#include "CItemFactory.h"

using namespace std;

int CAnthill::act() {

	/* generate ants place them near the anthill */
	CEnvironment &environment = CEnvironment::getInstance();

	int create = environment.getTurncnt() % 5;
	if (environment.getTurncnt() == 1) {
		create = 0;
	}

	if (this->food >= 20 && create == 0 && (this->make == true)) {

		this->make = true;
		CItemFactory *myGameFactory = new CItemFactory();
		CAnt* ant = dynamic_cast<CAnt*>(myGameFactory->newItem("ant"));

		/* Mark the ant as ant of this anthill*/
		ant->setOriginAnthill(this);

		ant->setM(this->M + 1);
		ant->setN(this->N + 1);

		CEnvironment &environment = CEnvironment::getInstance();
		environment.getPlayground()->getArea(ant->getM(), ant->getN())->addItemToList(ant);

		this->antcount++;

	}

	//print();

	//cout << this->food << "\n";
	return 0;
}

void CAnthill::print() {
	cout << "H";
}

void CAnthill::addAntToAnthill(CItem *ant) {

	/*
	 *  insert ant into list of ants
	 *  push it at front and take it from
	 *  check if we realy get an ant back :-)
	 */

	try {
		this->antList.push_front(dynamic_cast<CAnt*>(ant));
	} catch (bad_cast&) {
		cout << "That was not an ant!";
	}

}

CAnthill::CAnthill(int defFood) {

	/*
	 * default values
	 */

	this->antcount = 0;
	this->antdiecount = 0;
	this->classType = "anthill";

	/*
	 * Define the food count inside the Anthill
	 * If the constructor is not initialized on creation
	 * the default value of the constructor in CAnthill.h is 200
	 */
	food = defFood;

	make = true;

	/*
	 * Get the environment singelton so I could calculate the M N random
	 */

	CEnvironment &environment = CEnvironment::getInstance();

	this->M = rand() % environment.getM();
	this->N = rand() % environment.getN();

	if (this->M == 0) {
		this->M = 1;
	}

	if (this->N == 0) {
		this->N = 1;
	}

	/*
	 * If we know where we are, place the Anthill himself into playground
	 * and store the N M values inside the the Anthill
	 */

	//environment.getPlayground()->getArea(M,N)->get(this);
//
//	list<CItem*> items = environment.getPlayground()->getArea(M,N)->getItemList();
//	items.push_back(this);
//	list<CItem*>::iterator it;
//	it = items.begin();
//	(*it)->act();
}

CAnthill::~CAnthill() {
	// TODO Auto-generated destructor stub
}

